package dk.ahp.getmeoff;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

/**
 * 
 * Activity for creating and editing destinations.
 */
public class AddDestActivity extends AbstractActivity implements OnClickListener, TextWatcher, SensorEventListener {
	private final String TAG = AddDestActivity.class.getSimpleName();
	private Button pickOnMapButton;
	private Button pickStartOnMapButton;
	private Button useCurrentPosButton;
	private Button saveDistButton;
	private TextView tv;
	private EditText ed;
	private Location startPos;
	
	private SensorManager sm = null;
	private float shock = 0;/// Brugt af sensor
	private float max=0, min=10000;/// Brugt af sensor
	private long lastResetTime=0;/// Brugt af sensor


	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_dist);
        
        pickOnMapButton = (Button) findViewById(R.id.findDistButton);
        pickOnMapButton.setOnClickListener(this);
        
        pickStartOnMapButton = (Button) findViewById(R.id.startDistOnMapButton);
        pickStartOnMapButton.setOnClickListener(this);
        
        useCurrentPosButton = (Button) findViewById(R.id.UseCurrentPosButton);
        useCurrentPosButton.setOnClickListener(this);
        
        saveDistButton = (Button) findViewById(R.id.saveDistButton);
        saveDistButton.setOnClickListener(this);
        
        View lay = (View) findViewById(R.id.addDistRelativeLayout);

        ed = (EditText) findViewById(R.id.distNameEditText1);

        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        
        setBackground(lay);
        
        Intent i = getIntent();
        Bundle b = i.getExtras();
        if (null != b) {
        	String s = b.getString("name");
        	GetMeOffApplication.getMeOffApplication.tmpDestination = GetMeOffApplication.getMeOffApplication.destinationLogic.getDestination(s);
        	saveDistButton.setText(R.string.Activate);
        	ed.setText(GetMeOffApplication.getMeOffApplication.tmpDestination.getName());
        	if (null != GetMeOffApplication.getMeOffApplication.activeDestination) {
        		String active = GetMeOffApplication.getMeOffApplication.activeDestination.getName();
        		if(active.equals(s)) {
        			saveDistButton.setText(R.string.deactivate);
        		}
        	} 
        } else {
        	GetMeOffApplication.getMeOffApplication.tmpDestination = new Destination("Ny", null, null, 0, null, null);
        }
        Log.d(TAG, "onCreate done");
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();
    	if (null == GetMeOffApplication.getMeOffApplication.tmpDestination){
        	GetMeOffApplication.getMeOffApplication.tmpDestination = new Destination("Ny", null, null, 0, null, null);
        } 
       	ed.setText(GetMeOffApplication.getMeOffApplication.tmpDestination.getName());
        String description = GetMeOffApplication.getMeOffApplication.tmpDestination.toString();
    	tv = (TextView) findViewById(R.id.destDescriptionTextView);
        tv.setText(description);

        ed.addTextChangedListener(this);// Ingen grund til at lytte før, jeg er færdig med at skrive i ed.

        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), 1000000000);
        
        Log.d(TAG, "onResume");
    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	ed.removeTextChangedListener(this);
    	sm.unregisterListener(this);
    	Log.d(TAG, "onPause");
    }
    
	@Override
	public void onClick(View v) {
		Log.d(TAG, "onClick: " + v.toString());
		
		if (pickOnMapButton == v)
		{
			Intent i = new Intent(this, DestMapActivity.class);
			i.putExtra("name", R.string.title_activity_dist_map);
			saveDistButton.setText(R.string.saveDist);
			startActivity(i);
		}
		else if (pickStartOnMapButton == v) {
			Intent i = new Intent(this, DestMapActivity.class);
			i.putExtra("name", R.string.title_activity_dist_map_start);
			saveDistButton.setText(R.string.saveDist);
			startActivity(i);
		}
		else if (useCurrentPosButton == v) {
			startPos = GetMeOffApplication.getMeOffApplication.currentLocation;
			if(null != startPos) {
				GetMeOffApplication.getMeOffApplication.tmpDestination.setStart(startPos);
			} 
			String description = GetMeOffApplication.getMeOffApplication.tmpDestination.toString();
			tv.setText(description);
			Log.d(TAG, description);
			saveDistButton.setText(R.string.saveDist);
		} 
		else if (saveDistButton == v) {
			if (saveDistButton.getText().equals(getResources().getString(R.string.Activate))) {
				GetMeOffApplication.getMeOffApplication.activeDestination = GetMeOffApplication.getMeOffApplication.tmpDestination;
				GetMeOffApplication.getMeOffApplication.distanceToDest = 0;
				GetMeOffApplication.getMeOffApplication.updateThread.interrupt();
				finish();
			} else if (saveDistButton.getText().equals(getResources().getString(R.string.deactivate))) {
				GetMeOffApplication.getMeOffApplication.activeDestination = null;
				GetMeOffApplication.getMeOffApplication.distanceToDest = 0;
				GetMeOffApplication.getMeOffApplication.updateThread.interrupt();
				finish();
			} else {
				GetMeOffApplication.getMeOffApplication.destinationLogic.SaveDestination(GetMeOffApplication.getMeOffApplication.tmpDestination);
				saveDistButton.setText(R.string.Activate);
			}
		}
	}

    @Override
    public void afterTextChanged(Editable s) {
    	Log.d(TAG, "afterTextChanged " + s.toString());
    	GetMeOffApplication.getMeOffApplication.tmpDestination.setName(s.toString());
    	tv.setText(GetMeOffApplication.getMeOffApplication.tmpDestination.toString());
    	saveDistButton.setText(R.string.saveDist);
    }

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// Skal ikke bruges
	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// Skal ikke bruges
	}
	
    @Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
    	// Skal ikke bruges
    }

    /**
     * Reseter destiantion når der rystes.
     */
	@Override
	public void onSensorChanged(SensorEvent event) 
	{
		//Log.d(TAG, "SensorEvent");
		float[] values = event.values;
        //Log.d(TAG+":onSensorChanged", "" + event.sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
	 	if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
	 	{
        	float newAccel = Math.abs(values[0]) + Math.abs(values[1]) + Math.abs(values[2]);
        	if (newAccel > max)
        		max = newAccel;
        	if(newAccel < min)
        		min = newAccel;
        	if (Math.abs(newAccel - shock) > 1)
        	{
        		shock = newAccel;
        		Log.d(TAG,"new shock " + shock);
        	}
        	long sysTime = System.currentTimeMillis();
        	long diff = sysTime-lastResetTime;
        	if(newAccel>30 && (diff>2000)) //reset ikke flere gange i sekundet.
        	{
        		Log.d(TAG+":onSensorChanged", "Resetter current destination");
        		lastResetTime = sysTime;
        		GetMeOffApplication.getMeOffApplication.tmpDestination = new Destination("Ny", null, null, 0, null, null);
               	ed.setText(GetMeOffApplication.getMeOffApplication.tmpDestination.getName());
                String description = GetMeOffApplication.getMeOffApplication.tmpDestination.toString();
                tv.setText(description);
        	}
        }            
	}

}
